package middlerware

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm-demo/model/dto"
	"gorm-demo/service/user"
	"gorm-demo/utils"
	"log"
	"net/http"
)

func check(path string) bool {
	fmt.Println("path:", path)
	if path == "/login" || path == "/register" {
		return true
	}
	return false
}
func LoginIntercept() gin.HandlerFunc {
	return func(c *gin.Context) {
		//排除接口
		if check(c.Request.URL.Path) {
			c.Next()
			return
		}
		token := c.GetHeader("authorization")
		if token == "" {
			c.JSON(http.StatusForbidden, gin.H{"msg": "请先登录"})
			c.Abort()
			return
		}
		//	校验token
		_, err := utils.ValidateJwt(token)
		if err != nil {
			c.JSON(http.StatusForbidden, gin.H{"msg": err.Error()})
			c.Abort()
			return
		}
		id, _ := utils.GetUserId(token)
		if !utils.Exists(token) {
			permissionList := user.GetPermissionTreeByUid(id)
			marshal, _ := json.Marshal(permissionList)
			utils.Add(token, string(marshal))
		} else {
			fmt.Println(utils.Get(token))
			get := utils.Get(token)
			var p dto.PermissionList
			err := json.Unmarshal([]byte(get), &p)
			if err != nil {
				log.Default().Println(err)
				return
			}
		}
		c.Next()
	}
}
